using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BardsTaleViewer {
  public static class RLE {
    public static byte[] Decode (byte [] bufferSrc, ref int offsetSrc) {
      byte [] bufferDst = new byte [65000];
      int offsetDst = 0;
      for (; ; ) {
        int b = bufferSrc.ReadByte (ref offsetSrc);
        if (b == 0)
          break;
        if ((b & 0x80) != 0) {
          b &= 0x7F;
          for (; ; ) {
            if (b == 0)
              break;
            if (offsetSrc == bufferSrc.Length)
              return (bufferDst.Extract (0, offsetDst));
            bufferDst.WriteByte (offsetDst, bufferSrc.ReadByte (ref offsetSrc));
            offsetDst++;
            b--;
          }
        }
        else {
          int b2 = bufferSrc.ReadByte (ref offsetSrc);
          for (; ; ) {
            if (b == 0)
              break;
            bufferDst.WriteByte (offsetDst, b2);
            offsetDst++;
            b--;
          }
        }
      }
      //Console.WriteLine ("{0} / {1}", offsetSrc, bufferSrc.Length);
      return (bufferDst.Extract (0, offsetDst));
    }
  }
}
